package edu.pw.p2pclient.networking.webservice;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;

public class WebServiceTask extends AsyncTask<Void, Void, Response> {

	public static final String BASE_URI = "http://192.168.0.100/";
	private static final String TAG = "WebServiceTask";

	protected String mReqAddress;
	protected List<NameValuePair> mNameValuePairs;
	private Type mResponseType;

	private HttpClient mHttpClient = null;
	private static Gson mGson = null;

	static {
		GsonBuilder builder = new GsonBuilder();
		builder.enableComplexMapKeySerialization().serializeNulls();
		builder.registerTypeAdapter(Response.class, Response.deserializer);
		builder.registerTypeAdapter(ActiveRequestsResponse.class,
				ActiveRequestsResponse.deserializer);
		builder.registerTypeAdapter(ActiveRequest.class,
				ActiveRequest.deserializer);
		builder.registerTypeAdapter(ResourcesResponse.class,
				ResourcesResponse.deserializer);
		builder.registerTypeAdapter(FoundResource.class,
				FoundResource.deserializer);
		mGson = builder.create();
	}

	public WebServiceTask(String reqAddress, List<NameValuePair> nameValuePairs) {
		this(reqAddress, nameValuePairs, Response.class);
	}

	public WebServiceTask(String reqAddress,
			List<NameValuePair> nameValuePairs, Type responseType) {
		mReqAddress = reqAddress;
		mNameValuePairs = nameValuePairs;
		mResponseType = responseType;
	}

	public void inBackgroundPre() {

	}

	@Override
	protected Response doInBackground(Void... params) {
		inBackgroundPre();
		if (mHttpClient == null)
			mHttpClient = new DefaultHttpClient();
		Response response = null;
		BufferedReader rd = null;
		HttpPost req = new HttpPost(BASE_URI + mReqAddress);

		try {
			req.setEntity(new UrlEncodedFormEntity(mNameValuePairs));
			HttpResponse resp = mHttpClient.execute(req);
			rd = new BufferedReader(new InputStreamReader(resp.getEntity()
					.getContent()));

			StringBuilder respBuilder = new StringBuilder();
			String line = "";
			while ((line = rd.readLine()) != null)
				respBuilder.append(line);
			resp.getEntity().consumeContent();
			String responseStr = respBuilder.toString();
			try {
				response = mGson.fromJson(responseStr, mResponseType);
			} catch (JsonSyntaxException ex) {
				ex.printStackTrace();
			}
			Log.i(TAG, mReqAddress + " called. Received response: "
					+ responseStr);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (rd != null) {
				try {
					rd.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return response;
	}

}
